package v1

import (
	"sweetsunnyflower/app/models/address"
	"sweetsunnyflower/app/policies"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/response"

	"github.com/gin-gonic/gin"
)

type AddressesController struct {
	Controller
}

func (ctrl *AddressesController) Index(c *gin.Context) {

	addresses, err := address.GetByCache()
	if err != nil {
		response.Error(c, err)
	}

	response.Data(c, addresses)
}

func (ctrl *AddressesController) Show(c *gin.Context) {
	addressModel := address.Get(c.Param("id"))
	if addressModel.ID == 0 {
		response.Abort404(c)
		return
	}
	response.Data(c, addressModel)
}

func (ctrl *AddressesController) Store(c *gin.Context) {

	request := requests.AddressRequest{}
	if ok := requests.Validate(c, &request, requests.AddressSave); !ok {
		return
	}

	addressModel := address.Address{
		// FieldName:      request.FieldName,
	}
	addressModel.Create()
	if addressModel.ID > 0 {
		response.Created(c, addressModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *AddressesController) Update(c *gin.Context) {

	addressModel := address.Get(c.Param("id"))
	if addressModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyAddress(c, addressModel); !ok {
		response.Abort403(c)
		return
	}

	request := requests.AddressRequest{}
	if ok := requests.Validate(c, &request, requests.AddressSave); !ok {
		return
	}

	// addressModel.FieldName = request.FieldName
	rowsAffected := addressModel.Save()
	if rowsAffected > 0 {
		response.Data(c, addressModel)
	} else {
		response.Abort500(c, "更新失败，请稍后尝试~")
	}
}

func (ctrl *AddressesController) Delete(c *gin.Context) {

	addressModel := address.Get(c.Param("id"))
	if addressModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyAddress(c, addressModel); !ok {
		response.Abort403(c)
		return
	}

	rowsAffected := addressModel.Delete()
	if rowsAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败，请稍后尝试~")
}
